package com.woniuxy.cloud.carl.marketing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.cloud.carl.carlgoods.client.SkuQueryClient;
import com.woniuxy.cloud.carl.carlgoods.client.dto.SkuDto;
import com.woniuxy.cloud.carl.marketing.client.param.AddScoreMallParam;
import com.woniuxy.cloud.carl.marketing.client.param.ExchangeGoodsParam;
import com.woniuxy.cloud.carl.marketing.client.result.ScoreLogDto;
import com.woniuxy.cloud.carl.marketing.common.StatusEnum;
import com.woniuxy.cloud.carl.marketing.infra.model.*;
import com.woniuxy.cloud.carl.marketing.infra.mapper.ScoreMallMapper;
import com.woniuxy.cloud.carl.marketing.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.cloud.carl.marketing.service.servicedto.ScoreCouponServiceDto;
import com.woniuxy.cloud.carl.marketing.service.servicedto.ScoreMallServiceDto;
import com.woniuxy.cloud.carl.marketing.service.servicedto.ScoreSkuServieDto;
import com.woniuxy.cloud.carl.order.client.OrderManageClient;
import com.woniuxy.cloud.carl.order.client.param.AddOneOrderParam;
import com.woniuxy.cloud.carl.user.client.AddressClient;
import com.woniuxy.cloud.carl.user.client.UserManageClient;
import com.woniuxy.cloud.carl.user.client.UserQueryClient;
import com.woniuxy.cloud.carl.user.client.param.GetByConditionParam;
import com.woniuxy.cloud.carl.user.client.result.AddressDto;
import com.woniuxy.cloud.carl.user.client.result.UserDetailDto;
import com.woniuxy.exceptions.MallException;
import com.woniuxy.result.CommonResultCodeEnum;
import com.woniuxy.result.Result;
import com.woniuxy.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 积分商城表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2023-07-19
 */
@Service
public class ScoreMallServiceImpl extends ServiceImpl<ScoreMallMapper, ScoreMall> implements ScoreMallService {
    @Autowired
    DeductionService deductionService;
    @Autowired
    FullDiscountCouponService fullDiscountCouponService;
    @Autowired
    ServiceCouponService serviceCouponService;
    @Autowired
    CouponService couponService;
    @Autowired
    ScoreLogService scoreLogService;
    @Autowired
    SkuQueryClient skuQueryClient;
    @Autowired
    OrderManageClient orderManageClient;
    @Autowired
    UserQueryClient userQueryClient;
    @Override
    public Result addScoreMall(AddScoreMallParam param) {
        ScoreMall scoreMall = BeanUtil.copyProperties(param, ScoreMall.class);
        if (param.getCouponId()!=null){
            ServiceCoupon coupon = serviceCouponService.getById(param.getCouponId());
            Deduction deduction = deductionService.getById(param.getCouponId());
            FullDiscountCoupon discountCoupon = fullDiscountCouponService.getById(param.getCouponId());
            if (coupon==null&&deduction==null&&discountCoupon==null)
                throw new MallException(CommonResultCodeEnum.DATA_NOT_FOUND,"优惠券信息错误");
        }
        save(scoreMall);
        return Result.success(CommonResultCodeEnum.SUCCESS,"添加成功",null);
    }

    @Override
    public Result delScoreMall(Long scoreMallGoodsId) {
        ScoreMall scoreMall = new ScoreMall();
        scoreMall.setScoreMallGoodsId(scoreMallGoodsId);
        scoreMall.setStatus(1);
        boolean b = updateById(scoreMall);
        if (b) return Result.success();
        return Result.fail("商品信息不存在");
    }
    @Autowired
    UserManageClient userManageClient;
    @Autowired
    AddressClient addressClient;
    @Override
    public Result exchangeGoods(ExchangeGoodsParam param) {
        ScoreMall scoreMall = getById(param.getScoreMallGoodsId());
        Assert.state(scoreMall!=null,"商品信息错误");
        //判断积分够不够
        Result<UserDetailDto> userDetail1 = userQueryClient.getUserDetail(param.getUserId());
        UserDetailDto data = userDetail1.getData();
        Assert.state(data.getScore()<scoreMall.getScore(),"积分不足");
        //用户扣减积分
        userManageClient.useCode(param.getUserId(),scoreMall.getScore());
        if (scoreMall.getCouponId()==null){
            //兑换商品
            //调接口创建订单
//            GetByConditionParam getByConditionParam = new GetByConditionParam();
//            getByConditionParam.setPageNum(1);
//            getByConditionParam.setPageSize(5);
//            userQueryClient.getByCondition(getByConditionParam);
            Result<UserDetailDto> userDetail = userDetail1;
            //判断地址信息对不对头
            Result<List<AddressDto>> all = addressClient.findAll(param.getUserId().intValue());
            List<Long> collect = all.getData().stream().map(o -> o.getAddressId()).collect(Collectors.toList());
            if (!collect.contains(param.getAddrId()))
                throw new MallException(CommonResultCodeEnum.DATA_NOT_FOUND,"地址信息错误");
            AddOneOrderParam orderParam = new AddOneOrderParam();
            orderParam.setUserId(param.getUserId());
            orderParam.setUserName(userDetail.getData().getUserName());
            orderParam.setAddressId(param.getAddrId());
            orderParam.setRemarks("积分兑换");
            orderParam.setIsInvoicing(1);
//            orderParam.setUserCarId(null);
//            orderParam.setPayMethod(null);
//            orderParam.setCouponId(null);
            BigDecimal bigDecimal = new BigDecimal(0);
            orderParam.setOriginalTotal(bigDecimal);
            orderParam.setDiscountAmount(bigDecimal);
            orderParam.setGoodsTotal(bigDecimal);
            orderParam.setServiceTotal(bigDecimal);
            orderParam.setCouponAmount(bigDecimal);
            orderParam.setFreight(bigDecimal);
            orderParam.setRealTotal(bigDecimal);
            orderParam.setRealPay(bigDecimal);
//            orderParam.setServiceId(null);
            orderParam.setSkuId(scoreMall.getSkuId());
            orderParam.setCount(1);
//            orderParam.setStoreId(null);
//            orderParam.setCouponType(null);
            orderManageClient.createOneOrder(orderParam);
        }else {
            //兑换优惠券
            Coupon coupon = new Coupon();
            ServiceCoupon serviceCoupon = serviceCouponService.getById(scoreMall.getCouponId());
            FullDiscountCoupon discountCoupon = fullDiscountCouponService.getById(scoreMall.getCouponId());
            Deduction deduction = deductionService.getById(scoreMall.getCouponId());
            if (serviceCoupon!=null){
                if (serviceCoupon.getStartDate2()!=null){
                    coupon.setStartTime(serviceCoupon.getStartDate2());
                    coupon.setEndTime(serviceCoupon.getEndDate2());
                }else {
                    Date date = new Date();
                    coupon.setStartTime(date);
                    coupon.setEndTime(new Date(date.getTime()+serviceCoupon.getCouponTime2()*24*60*60*1000));
                }
                coupon.setCouponNum(serviceCoupon.getServiceCouponId());
                coupon.setImage(serviceCoupon.getImage());
                coupon.setCouponContent(serviceCoupon.getCouponName2());
                coupon.setCouponType(serviceCoupon.getTypeFlag().longValue());
            }
            if (discountCoupon!=null){
                if (discountCoupon.getStartDate()!=null){
                    coupon.setStartTime(discountCoupon.getStartDate());
                    coupon.setEndTime(discountCoupon.getEndDate());
                }else {
                    Date date = new Date();
                    coupon.setStartTime(date);
                    coupon.setEndTime(new Date(date.getTime()+discountCoupon.getCouponTime()*24*60*60*1000));
                }
                coupon.setCouponNum(discountCoupon.getFullDiscountCouponId());
                coupon.setImage(discountCoupon.getImage());
                coupon.setCouponContent(discountCoupon.getCouponName());
                coupon.setCouponType(discountCoupon.getTypeFlag().longValue());
            }
            if (deduction!=null){
                if (deduction.getStartDate()!=null){
                    coupon.setStartTime(deduction.getStartDate());
                    coupon.setEndTime(deduction.getEndDate());
                }else {
                    Date date = new Date();
                    coupon.setStartTime(date);
                    coupon.setEndTime(new Date(date.getTime()+deduction.getCouponTime()*24*60*60*1000));
                }
                coupon.setCouponNum(deduction.getDeductionId());
                coupon.setImage(deduction.getImage());
                coupon.setCouponContent(deduction.getCouponName());
                coupon.setCouponType(deduction.getTypeFlag().longValue());
            }
            coupon.setUserId(param.getUserId());
            coupon.setCouponId(scoreMall.getCouponId());
            coupon.setCouponStatus(StatusEnum.USER_COUPON_NOT_USE.getCode());
            couponService.save(coupon);
        }

        //生成兑换记录
        ScoreLog scoreLog = new ScoreLog();
        scoreLog.setScoreLogId(scoreMall.getScoreMallGoodsId());
        scoreLog.setScore(scoreMall.getScore().longValue());
        scoreLog.setUserId(param.getUserId());
        scoreLog.setReason(1);
        scoreLog.setCreateDate(new Date());
        scoreLog.setScoreMallGoodsId(param.getScoreMallGoodsId());
        scoreLogService.save(scoreLog);
        return Result.success();
    }

    @Override
    public ScoreMallServiceDto getScoreMall() {
        List<ScoreMall> list = list();
        ArrayList<ScoreSkuServieDto> scoreSkuServieDtos = new ArrayList<>();
        ArrayList<ScoreCouponServiceDto> scoreCouponServiceDtos = new ArrayList<>();
        for (ScoreMall scoreMall : list) {
            if (scoreMall.getCouponId()!=null){
                ScoreCouponServiceDto serviceDto = BeanUtil.copyProperties(scoreMall, ScoreCouponServiceDto.class);
                scoreCouponServiceDtos.add(serviceDto);
            }else {
                ScoreSkuServieDto servieDto = BeanUtil.copyProperties(scoreMall, ScoreSkuServieDto.class);
                scoreSkuServieDtos.add(servieDto);
            }
        }
        ScoreMallServiceDto scoreMallServiceDto = new ScoreMallServiceDto();
        scoreMallServiceDto.setScoreCouponServiceDtos(scoreCouponServiceDtos);
        scoreMallServiceDto.setScoreSkuServieDtos(scoreSkuServieDtos);
        return scoreMallServiceDto;
    }

    @Override
    public Result<List<ScoreLogDto>> getMyScoreLog(Long userId) {
        ArrayList<ScoreLogDto> scoreLogDtos = new ArrayList<>();
        List<ScoreLog> logList = scoreLogService.list(new QueryWrapper<ScoreLog>().eq("user_id", userId));
        logList.forEach(o->{
            ScoreLogDto scoreLogDto = BeanUtil.copyProperties(o, ScoreLogDto.class);
            ScoreMall scoreMall = getById(o.getScoreMallGoodsId());
            if (scoreMall.getCouponId()!=null){
                //积分商品为优惠券
                ServiceCoupon serviceCoupon = serviceCouponService.getById(scoreMall.getCouponId());
                FullDiscountCoupon discountCoupon = fullDiscountCouponService.getById(scoreMall.getCouponId());
                Deduction deduction = deductionService.getById(scoreMall.getCouponId());
                if (serviceCoupon!=null)
                    scoreLogDto.setName(serviceCoupon.getCouponName2());
                if (scoreLogDto.getName()==null&&discountCoupon!=null)
                    scoreLogDto.setName(discountCoupon.getCouponName());
                if (deduction!=null&&scoreLogDto.getName()==null)
                    scoreLogDto.setName(deduction.getCouponName());
            }else {
                //积分商品为sku
                Result<SkuDto> sku = skuQueryClient.findSkuById(scoreMall.getSkuId());
                scoreLogDto.setName(sku.getData().getSkuName());
            }
            scoreLogDtos.add(scoreLogDto);
        });
        return Result.success(scoreLogDtos);
    }
}
